package org.example.coffeeshoporderingsystem.order.controller;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import org.example.coffeeshoporderingsystem.common.controller.BaseController;
import org.example.coffeeshoporderingsystem.common.ui.UIManager;
import org.example.coffeeshoporderingsystem.common.util.SpringContextUtil;
import org.example.coffeeshoporderingsystem.member.util.MemberUtil;
import org.example.coffeeshoporderingsystem.order.dto.AddProductDTO;
import org.example.coffeeshoporderingsystem.order.entity.OrderDetail;
import org.example.coffeeshoporderingsystem.order.service.OrderService;
import org.example.coffeeshoporderingsystem.product.entity.Product;
import org.example.coffeeshoporderingsystem.product.service.CategoryService;
import org.example.coffeeshoporderingsystem.product.service.ProductService;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import static javafx.scene.paint.Color.*;

public class OrderController extends BaseController {
    public ToolBar categoryButtonToolBar;
    public GridPane productGridPane;
    public Label memberLabel;
    public TableView<OrderDetail> orderDetailTablView;
    public TableColumn<OrderDetail,Integer> orderDetailIdTabCol;
    public TableColumn<OrderDetail,String> productNameTabCol;
    public TableColumn<OrderDetail,Integer> countTabCol;
    public TableColumn<OrderDetail,Double> sumTabCol;
    public Label totalCountLabel;
    public Label totalMoneyLabel;
    // 优惠卷对话框
    public DialogPane couponDialogPane;
    // 数量对话框
    public DialogPane numberDialogPane;
    // 订单详情对话框
    public DialogPane showOrderInfoDialogPane;
    private CategoryService categoryService = SpringContextUtil.getBean(CategoryService.class);
    private ProductService productService = SpringContextUtil.getBean(ProductService.class);
    private OrderService orderService = SpringContextUtil.getBean(OrderService.class);
    private ObservableList orderDetailObservableList = FXCollections.observableArrayList();


    public void addOrUpdateCountProduct(Product product,Integer count)  {
        var addProductDTO = new AddProductDTO(product,count) ;
        var addRs = orderService.saveOrUpdateProduct(addProductDTO) ;
        if(addRs) {
            loadOrderDetail() ;
        }
    }

    public void loadOrderDetail(){
        if(MemberUtil.getMember()==null){
            return ;
        }
        orderDetailObservableList.clear();
        var order = orderService.findByCurrMember() ;
        var orderDetailList = order.getOrderDetailList() ;
        orderDetailObservableList.addAll(orderDetailList);
        totalMoneyLabel.setText(order.getTotalAmount()+"");
        /*totalCountLabel.setText(orderDetailList.stream().reduce(0.0,orderDetail->{
            return orderDetail.getQuantity();
        })+"");*/
    }

    public void chooseMember() throws IOException {
        UIManager.switchToMemberList();
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        // 绑定表格
        orderDetailTablView.setItems(orderDetailObservableList);
        // 绑定表格数据
        orderDetailIdTabCol.setCellValueFactory(new PropertyValueFactory<>("detailId"));
        productNameTabCol.setCellValueFactory(cellData->new SimpleStringProperty(cellData.getValue().getProduct().getName()));
        countTabCol.setCellValueFactory(new PropertyValueFactory<>("quantity"));
        sumTabCol.setCellValueFactory(new PropertyValueFactory<>("subtotal"));


        this.loadOrderDetail();
        // 设置会员信息
        var currMember = MemberUtil.getMember() ;
        if(currMember!=null) {
            memberLabel.setText(currMember.getMemberId()+"("+currMember.getName()+")");
        }

        // 设置 productGridPane 边框
        productGridPane.setStyle("-fx-border-color: #259b24;");
        productGridPane.setHgap(10);
        productGridPane.setVgap(10);
        productGridPane.setGridLinesVisible(true);
        // 获得产品类别
        var categoryList = categoryService.findAll();
        // 根据 类别动态创建 button
        var btnList = categoryList.stream().map(category -> {
            var button = new Button(category.getName());
            button.setPrefHeight(39);
            button.setPrefWidth(91);
            button.setStyle("-fx-background-color: #fff;");
            return button ;
        }).toList() ;

        // 注册事件
        btnList.forEach(button -> {
            button.setOnAction(event -> {
                var btn = categoryButtonToolBar.getItems().indexOf(button) ;
                var categoryId = categoryList.get(btn).getCategoryId();
                var productList = productService.findByCategoryId(categoryId);
                productGridPane.getChildren().clear();
                productList.forEach(product -> {
                    var anchorPane = new AnchorPane();
                    // 设置 AnchorPane 边框 颜色
                    anchorPane.setPrefHeight(200);
                    anchorPane.setPrefWidth(200);
                    anchorPane.setStyle("-fx-background-color: #fff;");
                    var label1 = new Label(product.getName());
                    label1.setLayoutX(14);
                    label1.setLayoutY(14);
                    label1.setPrefHeight(39);
                    label1.setPrefWidth(113);
                    label1.setFont(Font.font("Microsoft YaHei UI", 14));
                    label1.setText(product.getName()) ;
                    anchorPane.getChildren().add(label1);
                    var label2 = new Label("剩余："+product.getIsAvailable());
                    label2.setLayoutX(18);
                    label2.setLayoutY(106);
                    label2.setPrefHeight(39);
                    label2.setPrefWidth(105);
                    label2.setFont(Font.font("Microsoft YaHei UI", 14));
                    label2.setText("￥"+product.getPrice()) ;
                    label2.setTextFill(RED);
                    anchorPane.getChildren().add(label2);
                    var imageView = new ImageView();
                    imageView.setFitHeight(50);
                    imageView.setFitWidth(222);
                    imageView.setLayoutX(14);
                    imageView.setLayoutY(56);
                    imageView.setPickOnBounds(true);
                    imageView.setPreserveRatio(true);
                    imageView.setImage(new Image(product.getImageUrl()));
                    anchorPane.getChildren().add(imageView);

                    anchorPane.setOnMouseClicked(eve -> {
                        addOrUpdateCountProduct(product,1) ;
                    });
                    anchorPane.setOnMouseEntered(eve -> {
                        // 设置背景色 #8bc34a
                        anchorPane.setStyle("-fx-background-color: #8bc34a;");
                        // 设置字体颜色 白色
                        label1.setTextFill(WHITE);
                        label2.setTextFill(WHITE);
                    });
                    anchorPane.setOnMouseExited(eve -> {
                        // 设置背景色 #8bc34a
                        anchorPane.setStyle("-fx-background-color: #fff;");
                        // 设置字体颜色 白色
                        label1.setTextFill(BLACK);
                        label2.setTextFill(RED);
                    });
                    productGridPane.add(anchorPane, productGridPane.getChildren().size() % 2, productGridPane.getChildren().size() / 2);
                });
                for (int i = 0; i < btnList.size(); i++) {
                    if(i==btn) {
                        button.setStyle("-fx-background-color: #259b24;");
                        button.setTextFill(WHITE);
                    }else{
                        btnList.get(i).setStyle("-fx-background-color: #fff;");
                        btnList.get(i).setTextFill(BLACK);
                    }
                }

            });
        }) ;

        // 默认触发 第一个按钮
        /*new Thread(()->{
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            btnList.get(0).fireEvent(new ActionEvent());
        }).start();*/
        categoryButtonToolBar.getItems().addAll(btnList) ;
        // 默认触发 第一个按钮 点击事件
        categoryButtonToolBar.getItems().getFirst().fireEvent(new ActionEvent());
    }

    public void submitOrder() {
        showOrderInfoDialogPane.setVisible(true);
        /*var order = orderService.findByCurrMember();
        if(order.getOrderDetailList().size()==0) {
            UIManager.showAlertWarn("订单不能为空");
            return ;
        }
        if(orderService.save(order)) {
            UIManager.showAlertInfo("下单成功");
            this.loadOrderDetail();
        }else{
            UIManager.showAlertError("下单失败");
        }*/
    }

    public void showCouponDialogPane() throws IOException {
        couponDialogPane.setVisible(true);
    }

    public void confirmCoupon() {
        couponDialogPane.setVisible(false);
    }

    public void closeCoupon() {
        couponDialogPane.setVisible(false);
    }

    public void showNumberDialogPane() {
        numberDialogPane.setVisible(true);
    }

    public void confirmNumber() {
        numberDialogPane.setVisible(false);
    }

    public void closeOrderInfoDialogPane() {
        showOrderInfoDialogPane.setVisible(false);
    }
}
